package LeetCode;

import java.util.ArrayList;
import java.util.List;

public class LC_282_ExpressionAddOperators {

    public static void main(String[] args) {

    }

    public List<String> addOperators(String num, int target) {
        List<String> ret = new ArrayList<String>();
        if (num == null || num.length() == 0) return ret;
        helper(ret, "", num, target, 0, 0, 0);
        return ret;
    }

    private void helper(List<String> ret, String path, String num, int target, int pos, long curRes, long preNum) {
        if (pos == num.length()) {
            if (target == curRes) ret.add(path);
            return;
        }
        for (int i = pos; i < num.length(); i++) {
            if (i != pos && num.charAt(pos) == '0') return;
            long curNum = Long.valueOf(num.substring(pos, i + 1));
            if (pos == 0) {
                helper(ret, path + curNum, num, target, i + 1, curNum, curNum);
            } else {
                helper(ret, path + "+" + curNum, num, target, i + 1, curRes + curNum, curNum);
                helper(ret, path + "-" + curNum, num, target, i + 1, curRes - curNum, -curNum);
                helper(ret, path + "*" + curNum, num, target, i + 1, curRes - preNum + preNum * curNum, preNum * curNum);
            }
        }
    }

}